package com.atguigu.gmall.realtime.utils;

import lombok.extern.slf4j.Slf4j;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * IK分词器工具类
 *
 * @author lvbingbing
 * @date 2022-07-06 15:17
 */
@Slf4j
public class KeywordUtils {

    /**
     * 使用IK分词器对字符串进行分词
     *
     * @param text <br>
     * @return <br>
     */
    public static List<String> analyze(String text) {
        StringReader sr = new StringReader(text);
        IKSegmenter ik = new IKSegmenter(sr, true);
        Lexeme lex;
        List<String> keywordList = new ArrayList<>();
        while (true) {
            try {
                if ((lex = ik.next()) != null) {
                    String lexemeText = lex.getLexemeText();
                    keywordList.add(lexemeText);
                } else {
                    break;
                }
            } catch (Exception e) {
                log.error("对字符串进行分词出现异常！入参：{}, 异常原因：{}", text, e);
            }
        }
        return keywordList;
    }

    public static void main(String[] args) {
        String text = "Apple iPhoneXSMax (A2104) 256GB 深空灰色 移动联通电信4G手机 双卡双待";
        List<String> stringList = KeywordUtils.analyze(text);
        log.info("分词结果：{}", stringList);
    }
}
